<template>
  <div class="common-layout">
    <el-container style="height: 100%;width:100%">
      <!-- 顶部导航栏 -->
      <el-header class="app-header">
        <div class="header-content">
					<div>
            <div class="divTitle">企业数智化信息平台</div>
						<el-button @click="loginOut"><el-icon><SwitchButton /></el-icon>注销</el-button>
						<el-button   @click="dialogFormVisible = true"><el-icon><EditPen /></el-icon>修改密码</el-button>
					</div>
        </div>
      </el-header>
      
      <el-container class="app-container">
        <!-- 侧边栏菜单 -->
        <el-aside width="220px" class="app-sidebar">
          <el-scrollbar>
            <!-- 加载状态 -->
            <div v-if="menuStore.isLoading" class="loading-state">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>菜单加载中...</span>
            </div>
            
            <!-- 错误状态 -->
            <div v-if="menuStore.error" class="error-state">
              <el-icon><Warning /></el-icon>
              <span>{{ menuStore.error }}</span>
              <el-button type="text" @click="menuStore.fetchMenus">重试</el-button>
            </div>
            
            <!-- 菜单渲染 -->
            <el-menu
              v-if="!menuStore.isLoading && !menuStore.error"
              :default-active="activeMenu"
              :default-openeds="openedMenus"
              :unique-opened="true"
              router
              class="app-menu"
            >
              <template v-for="menu in normalizedMenus" :key="menu.id">
                <!-- 有子菜单的情况 -->
                <el-sub-menu 
                  v-if="menu.children && menu.children.length > 0" 
                  :index="menu.index"
                >
                  <template #title>
                    <el-icon>
                      <component :is="iconComponents[menu.icon]" v-if="menu.icon" />
                    </el-icon>
                    <span>{{ menu.title }}</span>
                  </template>
                 
                  <el-menu-item 
                    v-for="child in menu.children" 
                    :key="child.id" 
                    :index="child.path"
                  >
                    <el-icon v-if="child.icon">
                      <component :is="child.icon" />
                    </el-icon>
                    <span>{{ child.title }}</span>
                  </el-menu-item>
                </el-sub-menu>
                
                <!-- 无子菜单的情况 -->
                <el-menu-item v-else :index="menu.path">
                  <el-icon>
                    <component :is="menu.icon" />
                  </el-icon>
                  <span>{{ menu.title }}</span>
                </el-menu-item>
              </template>
            </el-menu>
            
            <!-- 空状态 -->
            <div v-if="showEmptyState" class="empty-state">
              <el-icon><FolderOpened /></el-icon>
              <span>暂无菜单数据</span>
            </div>
          </el-scrollbar>
        </el-aside>
        
  <!-- 主内容区 -->
  <el-main class="app-main">
    <!-- 动态标签页 -->
    <div class="dynamic-tabs">
      <el-tabs
        v-model="activeTab"
        type="card"
        closable
        @tab-click="handleTabClick"
        @tab-remove="removeTab"
      >
        <el-tab-pane
          v-for="tab in tabs"
          :key="tab.path"
          :label="tab.title"
          :name="tab.path"
        >
          <!-- 使用 keep-alive 缓存页面 -->
          <keep-alive :include="cachedViews">
            <router-view
              v-if="tab.path === activeTab"
              :key="tab.path"
            />
          </keep-alive>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeMount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMenuStore } from '@/stores/menu'
import { 
  Loading, 
  Warning, 
  FolderOpened,
  Message,
  Menu as IconMenu,
  Setting,
  User as Avatar,
  SwitchButton,
  EditPen
} from '@element-plus/icons-vue'  

const route = useRoute()
const router = useRouter()
const menuStore = useMenuStore()
// 动态标签页相关状态
const tabs = ref([])
const activeTab = ref('')
const cachedViews = ref(new Set()) // 用于 keep-alive 的缓存列表

// 图标名称映射
const iconComponents = {
  'Message': Message,
  'IconMenu': IconMenu,
  'Setting': Setting,
  'Avatar': Avatar
  // 添加其他需要的图标映射
}
// 从 sessionStorage 恢复状态
onBeforeMount(() => {
  const savedTabs = sessionStorage.getItem('tabs')
  const savedActiveTab = sessionStorage.getItem('activeTab')
  
  if (savedTabs) {
    tabs.value = JSON.parse(savedTabs)
    cachedViews.value = new Set(tabs.value.filter(t => t.cache).map(t => t.path))
  }
  
  if (savedActiveTab) {
    activeTab.value = savedActiveTab
  }
})

// 保存状态到 sessionStorage
const saveState = () => {
  sessionStorage.setItem('tabs', JSON.stringify(tabs.value))
  sessionStorage.setItem('activeTab', activeTab.value)
}

// 查找菜单项
const findMenuItem = (path) => {
  for (const menu of menuStore.menus) {
    if (menu.path === path) return menu
    if (menu.children) {
      const child = menu.children.find(child => child.path === path)
      if (child) return child
    }
  }
  return null
}

// 添加标签页
const addTab = (menuItem) => {
  const tabExists = tabs.value.some(tab => tab.path === menuItem.path)
  if (!tabExists) {
    tabs.value.push({
      title: menuItem.title,
      path: menuItem.path,
      icon: menuItem.icon,
      cache: menuItem.cache !== false // 默认缓存，除非显式设置为 false
    })
    
    // 如果需要缓存，添加到 cachedViews
    if (menuItem.cache !== false) {
      cachedViews.value.add(menuItem.path)
    }
  }
  activeTab.value = menuItem.path
  saveState()
}

// 移除标签页
const removeTab = (targetPath) => {
  const index = tabs.value.findIndex(tab => tab.path === targetPath)
  if (index !== -1) {
    tabs.value.splice(index, 1)
    cachedViews.value.delete(targetPath) // 从缓存中移除
    
    // 如果删除的是当前激活的标签页，需要激活另一个标签页
    if (targetPath === activeTab.value) {
      const newActiveTab = tabs.value[index] || tabs.value[index - 1]
      if (newActiveTab) {
        activeTab.value = newActiveTab.path
        router.push(newActiveTab.path)
      } else {
        // 如果没有标签页了，跳转到首页或第一个菜单项
        const firstMenuPath = menuStore.menus[0]?.path
        if (firstMenuPath) {
          router.push('/home')
        }
      }
    }
  }
  saveState()
}

// 处理标签页点击
const handleTabClick = (tab) => {
  const path = tab.paneName
  if (route.path !== path) {
    router.push(path)
  }
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  const menuItem = findMenuItem(newPath)
  if (menuItem) {
    addTab(menuItem)
  }
}, { immediate: true })

// 监听标签页变化
watch(tabs, saveState, { deep: true })
watch(activeTab, saveState)

// 初始化加载菜单
onMounted(() => {
  if (menuStore.menus.length === 0) {
    menuStore.fetchMenus()
  }
})
// 当前激活菜单
const activeMenu = computed(() => {
  return route.path || menuStore.menus[0]?.path
})

// 默认打开的菜单
const openedMenus = computed(() => {
  return menuStore.menus
    .filter(menu => menu.children?.some(child => child.path === activeMenu.value))
    .map(menu => menu.index)
})

// 标准化菜单数据（可添加额外处理）
const normalizedMenus = computed(() => {
  return menuStore.menus.map(menu => ({
    ...menu,
    // 确保子菜单也有完整路径
    children: menu.children?.map(child => ({
      ...child,
      path: child.path || `${menu.path}-${child.id}`
    }))
  }))
})

// 空状态显示
const showEmptyState = computed(() => {
  return !menuStore.isLoading && 
         !menuStore.error && 
         menuStore.menus.length === 0
})

// 初始化加载菜单
onMounted(() => {
  if (menuStore.menus.length === 0) {
    menuStore.fetchMenus().then(() => {
      console.log('最终菜单数据:', JSON.parse(JSON.stringify(menuStore.menus)));
    });
  }
});
</script>

<style scoped>
.el-button {				
  background-color: #545c64;
	border-color: #545c64;
	color: #fff;
	width: 80px;
	padding: 20px 5px;
	float: right;
}
.divTitle {
display: inline;
font-size: 32px;
line-height: 60px;
letter-spacing: 5px;
color: #fff;
padding-left: 60px;
background-image: url(img/logo.png);
background-repeat: no-repeat;
background-position-y: center;
}
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.app-header {
  --el-header-height: 60px;
  height: var(--el-header-height);
  background-color: #4F5E64;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  
  .header-content {
    width: 100%;
    
    .logo-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .logo {
        height: 36px;
        width: auto;
      }
      
      h1 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
      }
    }
  }
}

.app-container {
  height: calc(100vh - var(--el-header-height));
}

.app-sidebar {
  background-color: white;
  border-right: 1px solid #e6e6e6;
  
  .loading-state,
  .error-state,
  .empty-state {
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    text-align: center;
    
    .el-icon {
      font-size: 24px;
    }
  }
  
  .loading-icon {
    animation: rotating 2s linear infinite;
  }
  
  .error-state {
    color: #f56c6c;
  }
  
  .empty-state {
    color: #666;
  }
  
  .app-menu {
    border-right: none;
    
    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      height: 48px;
      line-height: 48px;
    }
    
    :deep(.el-menu-item.is-active) {
      background-color: var(--el-color-primary-light-9);
    }
  }
}

.app-main {
  padding: 20px;
  background-color: #f5f7fa;
  overflow: auto;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 新增动态标签页样式 */
.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.app-header {
  --el-header-height: 60px;
  height: var(--el-header-height);
  background-color: #4F5E64;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  
  .header-content {
    width: 100%;
    
    .logo-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .logo {
        height: 36px;
        width: auto;
      }
      
      h1 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
      }
    }
  }
}

.app-container {
  height: calc(100vh - var(--el-header-height));
  display: flex;
}

.app-sidebar {
  width: 220px;
  background-color: white;
  border-right: 1px solid #e6e6e6;
  overflow: hidden;
  
  /* 其他侧边栏样式保持不变 */
}

.app-main {
  flex: 1;
  padding: 0; /* 移除内边距 */
  background-color: #f5f7fa;
  overflow: auto;
}

.dynamic-tabs {
  height: 100%;
  
  :deep(.el-tabs) {
    height: 100%;
    display: flex;
    flex-direction: column;
    
    .el-tabs__header {
      margin: 0;
      padding: 0 20px;
      background-color: white;
      border-bottom: 1px solid #e6e6e6;
      
      .el-tabs__nav-wrap {
        padding-bottom: 0;
      }
    }
    
    .el-tabs__content {
      flex: 1;
      padding: 0; /* 移除内容区域的内边距 */
      overflow: auto;
    }
  }
}
</style>